package com.atguigu.gulimall.ware.service.impl;

import com.alibaba.fastjson.TypeReference;
import com.atguigu.common.to.mq.StockDetailTo;
import com.atguigu.common.to.mq.StockLockedTo;
import com.atguigu.common.utils.R;
import com.atguigu.common.vo.SkuHasStockVo;
import com.atguigu.gulimall.ware.entity.WareOrderTaskDetailEntity;
import com.atguigu.gulimall.ware.entity.WareOrderTaskEntity;
import com.atguigu.gulimall.ware.exception.NoStockException;
import com.atguigu.gulimall.ware.feign.OrderFeignService;
import com.atguigu.gulimall.ware.feign.ProductFeignService;
import com.atguigu.gulimall.ware.service.WareOrderTaskDetailService;
import com.atguigu.gulimall.ware.service.WareOrderTaskService;
import com.atguigu.gulimall.ware.vo.OrderItemVo;
import com.atguigu.gulimall.ware.vo.OrderTo;
import com.atguigu.gulimall.ware.vo.SkuWareHasStockVo;
import com.atguigu.gulimall.ware.vo.WareSkuLockVo;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.atguigu.common.utils.PageUtils;
import com.atguigu.common.utils.Query;

import com.atguigu.gulimall.ware.dao.WareSkuDao;
import com.atguigu.gulimall.ware.entity.WareSkuEntity;
import com.atguigu.gulimall.ware.service.WareSkuService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

@RabbitListener(queues = "stock.release.stock.queue")
@Service("wareSkuService")
public class WareSkuServiceImpl extends ServiceImpl<WareSkuDao, WareSkuEntity> implements WareSkuService {

    @Autowired
    private WareSkuDao wareSkuDao;

    @Autowired
    ProductFeignService productFeignService;

    @Autowired
    private WareOrderTaskService orderTaskService;

    @Autowired
    private WareOrderTaskDetailService orderTaskDetailService;

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Autowired
    private OrderFeignService orderFeignService;


    /**
     * 解锁库存的方法
     **/
    private void unLockStock(Long skuId, Long wareId, Integer num, Long taskDetailId) {
        baseMapper.unLockStock(skuId, wareId, num);
        WareOrderTaskDetailEntity detailEntity = new WareOrderTaskDetailEntity();
        detailEntity.setId(taskDetailId);
        detailEntity.setLockStatus(2);
        orderTaskDetailService.updateById(detailEntity);
    }

    @Override
    public PageUtils queryPage(Map<String, Object> params) {

        QueryWrapper<WareSkuEntity> queryWrapper = new QueryWrapper<>();
        String skuId = (String) params.get("skuId");
        if (!StringUtils.isEmpty(skuId)) {
            queryWrapper.eq("sku_id", skuId);
        }

        String wareId = (String) params.get("wareId");
        if (!StringUtils.isEmpty(wareId)) {
            queryWrapper.eq("ware_id", wareId);
        }

        IPage<WareSkuEntity> page = this.page(
                new Query<WareSkuEntity>().getPage(params),
                queryWrapper
        );

        return new PageUtils(page);
    }

    @Override
    public void addStock(Long skuId, Long wareId, Integer skuNum) {

        //1:判断如果还没有这个库存,就新增库存
        List<WareSkuEntity> skuEntities = wareSkuDao.selectList(new QueryWrapper<WareSkuEntity>().eq("sku_id", skuId).eq("ware_id", wareId));
        if (CollectionUtils.isEmpty(skuEntities)) {
            WareSkuEntity wareSkuEntity = new WareSkuEntity();
            wareSkuEntity.setSkuId(skuId);
            wareSkuEntity.setWareId(wareId);
            wareSkuEntity.setStock(skuNum);
            wareSkuEntity.setStockLocked(0);
            //TODO 远程查询sku信息,然后进行设置,成功则设置,失败就不需要处理,整个事务无需回滚
            try {
                R info = productFeignService.info(skuId);
                Map<String, Object> data = (Map<String, Object>) info.get("skuInfo");
                if (info.getCode() == 0) {
                    wareSkuEntity.setSkuName((String) data.get("skuNme"));
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            this.save(wareSkuEntity);
        } else {
            wareSkuDao.addStock(skuId, wareId, skuNum);
        }
    }

    /**
     * 批量查询sku是否还有库存
     **/
    @Override
    public List<SkuHasStockVo> getSkuStock(List<Long> skuIds) {
        List<SkuHasStockVo> collect = skuIds.stream().map(skuId -> {
            SkuHasStockVo stockVo = new SkuHasStockVo();
            //查询当前的总库存量
            Long count = baseMapper.getSkuStock(skuId);
            stockVo.setSkuId(skuId);
            stockVo.setHasStock(count == null ? false : count > 0);
            return stockVo;
        }).collect(Collectors.toList());
        return collect;
    }

    /**
     * 为订单的锁定商品库存
     * 库存解锁场景:
     * 1>下订单成功,订单过期妹纸支付被系统自动取消,被客户手动取消,都要解锁库存
     * 2>下订单成功,库存锁定成功,接下来的业务调用失败,导致订单回滚,之前锁定的库存就要自动解锁
     **/
    @Override
    @Transactional(rollbackFor = NoStockException.class)
    public Boolean orderLock(WareSkuLockVo vo) {

        /**
         * 保存库存工作单的详情,便于追溯
         **/
        WareOrderTaskEntity taskEntity = new WareOrderTaskEntity();
        taskEntity.setOrderSn(vo.getOrderSn());
        orderTaskService.save(taskEntity);

        //1:找到每个商品在哪个仓库都有库存
        List<OrderItemVo> locks = vo.getLocks();
        List<SkuWareHasStockVo> collect = locks.stream().map(item -> {
            SkuWareHasStockVo stockVo = new SkuWareHasStockVo();
            Long skuId = item.getSkuId();
            //查询这个商品在哪里有库存
            List<Long> ids = wareSkuDao.selectWareIds(skuId);
            stockVo.setWareId(ids);
            stockVo.setNum(item.getCount());
            return stockVo;
        }).collect(Collectors.toList());

        //锁定库存
        for (SkuWareHasStockVo hasStockVo : collect) {
            Boolean skuStock = false;
            Long skuId = hasStockVo.getSkuId();
            List<Long> wareIds = hasStockVo.getWareId();
            if (CollectionUtils.isEmpty(wareIds)) {
                //没有库存了
                throw new NoStockException(skuId);
            }
            //有库存,就扣减
            for (Long wareId : wareIds) {
                Integer result = wareSkuDao.lockSkuStock(skuId, wareId, hasStockVo.getNum());
                if (result == 1) {
                    skuStock = true;
                    //TODO 告诉MQ库存锁定成功
                    WareOrderTaskDetailEntity detailEntity = new WareOrderTaskDetailEntity();
                    detailEntity.setSkuId(skuId);
                    detailEntity.setSkuNum(hasStockVo.getNum());
                    detailEntity.setTaskId(taskEntity.getId());
                    detailEntity.setWareId(wareId);
                    detailEntity.setLockStatus(1);
                    orderTaskDetailService.save(detailEntity);

                    StockLockedTo lockedTo = new StockLockedTo();
                    lockedTo.setId(taskEntity.getId());
                    StockDetailTo stockDetailTo = new StockDetailTo();
                    BeanUtils.copyProperties(detailEntity, stockDetailTo);
                    lockedTo.setDetailTo(stockDetailTo);
                    rabbitTemplate.convertAndSend("stock-event-exchange", "stock.lock", lockedTo);
                    break;
                } else {
                    //当前仓库锁失败,重试下一个仓库
                }
            }
            if (skuStock = false) {
                //当前商品所有商品都没有锁成功,直接抛出异常
                throw new NoStockException(skuId);
            }
        }

        return true;
    }

    @Transactional
    @Override
    public void unLockStock(StockLockedTo to) {
        //库存工作单的ID
        Long id = to.getId();
        StockDetailTo detail = to.getDetailTo();
        Long detailId = detail.getId();
        //解锁
        //1:查询数据库关于这个订单的锁定库存信息,有就解锁,.没有,无需解锁
        /**
         * 要根据订单来判断是否需要解锁
         *    没有订单,必须解锁库存
         *    有订单,如果订单状态是已取消,解锁库存,其他状态,不能解锁
         **/
        WareOrderTaskDetailEntity byId = orderTaskDetailService.getById(detailId);
        if (byId != null) {
            //解锁
            WareOrderTaskEntity taskEntity = orderTaskService.getById(id);
            String orderSn = taskEntity.getOrderSn();
            //根据订单号,查询订单的状态
            R r = orderFeignService.getOrderStatus(orderSn);
            if (r.getCode() == 0) {
                OrderTo orderTo = r.getDate(new TypeReference<OrderTo>() {
                });
                //判断订单状态
                if (orderTo == null || orderTo.getStatus() == 4) {
                    //说明是 订单不存在或者订单为取消状态,需要解锁
                    if (byId.getLockStatus() == 1){
                        //当前库存工作单详情状态为1,已锁定但是未解锁才给你解锁
                        unLockStock(detail.getSkuId(), detail.getWareId(), detail.getSkuNum(), detailId);
                    }
                }
            }else {
                throw new RuntimeException("远程服务失败");
            }
        }
    }

    /**
     * 防止订单服务卡顿,导致订单状态消息一直改不了,库存消息优先到期,查询订单状态的时候订单一直处于新建状态,然后什么都不做就丢失了消息,导致卡顿的订单永远得不到解锁库存
     **/
    @Transactional
    @Override
    public void unLockStock(OrderTo vo) {

        String orderSn = vo.getOrderSn();
        WareOrderTaskEntity taskEntity = orderTaskService.getOrderTaskByOrderSn(orderSn);
        Long id = taskEntity.getId();
        //按照库存工作单,找到所有没有解锁的库存进行解锁
        List<WareOrderTaskDetailEntity> detailEntityList = orderTaskDetailService.list(new QueryWrapper<WareOrderTaskDetailEntity>().eq("task_id", id).eq("lock_status", 1));

        for (WareOrderTaskDetailEntity entity : detailEntityList) {
            unLockStock(entity.getSkuId(),entity.getWareId(),entity.getSkuNum(),entity.getId());
        }
    }
}
